/*
 * @Author: licc
 * @Date: 2021-03-08 15:00:30
 * @Last Modified by: jinqiang
 * @Last Modified time: 2021-11-04 18:01:52
 */

<template>
  <div class="xiaoxiToolbarClass">
    <el-popover
      v-model="visible"
      width="460"
      trigger="click"
      placement="bottom-start"
      popper-class="xiaoxiElementPopover"
      @show="onPopoverShow"
      ref="xiaoxiPopover"
    >
      <div class="xiaoxiPopoverScopedBody">
        <div class="xiaoxiHeader">
          <p>消息通知</p>
          <div class="xiaoxiHeaderRight">
            <el-tooltip
              content="全部标记已读"
              placement="top"
              :open-delay="500"
            >
              <i
                class="V7_iconfont V7_iconV7tubiao_quanbuyidu"
                @click="handleAllReadMessage"
              ></i>
            </el-tooltip>
            <el-tooltip
              content="清空已读消息"
              placement="top"
              :open-delay="500"
            >
              <i
                class="V7_iconfont V7_iconV7tubiao_shanchu"
                @click="handleDelReadMessage"
              ></i>
            </el-tooltip>
          </div>
        </div>
        <div class="xiaoxiCont xiaoxiElementTabs">
          <el-tabs
            v-model="listQuery.type"
            tab-position="left"
            style="height: 300px"
          >
            <!-- for循环生成tab-pane面板 -->
            <el-tab-pane
              v-for="pane in activeXiaoxiPane"
              :key="pane.tabPaneName"
              :name="pane.tabPaneName"
              v-loading="paneLoading"
              element-loading-text="初始化数据..."
            >
              <!-- 左侧列表自定义插槽 -->
              <div slot="label">
                <el-badge
                  :value="activeMsgListObj[pane.tabPaneName + 'NoReadCount']"
                  :max="pane.badgeMax"
                  :hidden="
                    activeMsgListObj[pane.tabPaneName + 'NoReadCount'] === 0 ||
                    pane.tabPaneName === 'star'
                  "
                >
                  {{ pane.tabPaneLabel }}
                </el-badge>
              </div>
              <!-- 没有消息的缺省提示 -->
              <div
                v-if="activeMsgListObj[pane.tabPaneName].length === 0"
                class="emptyPaneCont"
              >
                <img src="../../../assets/img/xiaoxiBarEmpty@3x.png" alt="" />
                <p>暂无通知～</p>
              </div>
              <!-- 有消息时的列表展示 -->
              <div v-else class="realPaneCont">
                <div
                  v-for="(msg, idx) in activeMsgListObj[pane.tabPaneName]"
                  :key="idx"
                  class="msgItemBody"
                >
                  <div class="msgItemCont" @click="handleReadMessage(msg)">
                    <!-- 消息头部 -->
                    <div class="msgHeader">
                      <div class="msgHeaderLeft">
                        <!-- 紧急程度 -->
                        <i
                          v-if="msg.levelNum === 3"
                          class="
                            V7_iconfont V7_iconV7tubiao_jinjixiaoxi
                            msgLevelIcon
                          "
                        ></i>
                        <i
                          v-if="msg.levelNum === 2"
                          class="
                            V7_iconfont V7_iconV7tubiao_zhongyaoxiaoxi
                            msgLevelIcon
                          "
                        ></i>
                        <!-- <i v-if="msg.levelNum === 1" class="iconfont putong buzhanshi"></i> -->
                        <!-- 标题 -->
                        <span
                          class="msgTitle"
                          :class="{
                            titleReadColor: msg.isRead,
                          }"
                          >{{ msg.name }}</span
                        >
                        <!-- 未读红点 -->
                        <i
                          v-if="!msg.isRead"
                          class="V7_iconfont V7_iconV7tubiao_dian"
                        ></i>
                      </div>
                      <div class="msgHeaderRight">
                        <!-- 时间 -->
                        <span class="msgTime">{{ msg.createTime }}</span>
                        <!-- 星标 -->
                        <span
                          class="msgStarIcon"
                          @click.stop="handleStarMessage(msg)"
                        >
                          <i
                            v-if="msg.isStar"
                            class="
                              V7_iconfont V7_iconV7tubiao_biaoxingxuanzhong
                            "
                          ></i>
                          <i
                            v-else
                            class="V7_iconfont V7_iconV7tubiao_biaoxingweixuan"
                          ></i>
                        </span>
                      </div>
                    </div>
                    <!-- 消息内容 -->
                    <div class="msgContainer">
                      <p
                        class="msgContent"
                        :class="{
                          contentReadColor: msg.isRead,
                          show2line: !msg.isExpand || msg.type === 'notice',
                        }"
                      >
                        {{ msg.content }}
                      </p>
                      <!-- hideDetails 为后端控制的值，是否展示查看详情，其他类型的也可以让后端返回 -->
                      <div v-show="msg.isExpand" class="msgBtnsBox">
                        <span
                          class="msgBtn iKnow"
                          @click.stop="handleIKnow(msg)"
                          >知道了</span
                        >
                        <span
                          class="msgBtn showInfo"
                          v-show="!msg.hideDetails"
                          @click.stop="handleShowInfo(msg)"
                          >查看详情</span
                        >
                      </div>
                    </div>
                    <!-- 正在打开 查看消息 的过度动画 -->
                    <div v-show="msg.isLoading" class="msgLoading">
                      <img
                        src="../../../assets/img/webchatLoading.gif"
                        alt=""
                      />
                      <span>加载中...</span>
                    </div>
                  </div>
                </div>
                <!-- 分页数、查看更多 -->
                <div class="listCountCont">
                  <div
                    v-if="
                      activeMsgListObj[pane.tabPaneName].length <
                      activeMsgListObj[pane.tabPaneName + 'Count']
                    "
                    class="loadMore"
                    @click="handleLoadMore"
                  >
                    点击加载更多
                  </div>
                  {{ activeMsgListObj[pane.tabPaneName].length }}
                  /
                  {{ activeMsgListObj[pane.tabPaneName + "Count"] }}
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
      <span slot="reference" style="position: relative">
        <i class="V7_iconfont V7_iconV7tubiao_xiaoxi"></i>
        <i
          v-show="activeMsgListObj.allNoReadCount > 0"
          class="V7_iconfont V7_iconV7tubiao_dian statusIcon"
        ></i>
      </span>
    </el-popover>
    <notice-drawer
      ref="NoticeDrawer"
      @closeDraw="closeNoticeDrawer"
    ></notice-drawer>
  </div>
</template>

<script lang="ts">
import { MessageModule } from '@/store/modules/message/sysMsg'
import { Component, Ref, Vue, Watch } from 'vue-property-decorator'
import NoticeDrawer from '@/views/home/components/NoticeDrawer.vue'
import { commonAction, getBellMessagePath } from '@/utils/common';
import { emitter } from '@/afterSales/utils/mmit';
@Component({
  name: 'XiaoxiToolbar',
  components: {
    NoticeDrawer
  }
})
export default class XiaoxiToolbar extends Vue {
  [x: string]: any
  @Ref() private readonly NoticeDrawer: any
  private visible: boolean = false
  private paneLoading: boolean = false
  private pageSize: number = 20
  private listQuery: any = {
    type: 'transmit'
  }

  private NoticeDrawerOpen: boolean = true

  private activeXiaoxiPane: any = [ // 获取消息面板及列表
    // {
    //   tabPaneLabel: '系统消息',
    //   tabPaneName: 'system',
    //   badgeMax: 99
    // },
    {
      tabPaneLabel: '传输中心',
      tabPaneName: 'transmit',
      badgeMax: 99
    },
    {
      tabPaneLabel: '星标通知',
      tabPaneName: 'star',
      badgeMax: 99
    },
    {
      tabPaneLabel: '公告通知',
      tabPaneName: 'notice',
      badgeMax: 99
    },
    {
      tabPaneLabel: '工单客户',
      tabPaneName: 'mpNotice',
      badgeMax: 99
    },
    {
      tabPaneLabel: '工单消息',
      tabPaneName: 'workorderNotice',
      badgeMax: 99
    },
    {
      tabPaneLabel: '质检消息',
      tabPaneName: 'qualityCheck',
      badgeMax: 99
    }
  ]

  @Watch('listQuery.type')
  private handleGetMsgList (val) {
    this.initData()
  }

  /** 获取消息面板及列表 */
  get activeMsgListObj () {
    const activeMsgListObj = this.$store.state.message.activeMsgListObj
    return activeMsgListObj
  }

  private getNoticeNum () {
    MessageModule.MessageCommonAction({
      url: '/base/action/message/unread/num',
      method: 'POST',
      hideLoading: true,
      data: {}
    }).then(resp => {
      if (resp && resp.success) {
        MessageModule.SET_NO_READ_COUNT(resp.data)
      }
    })
  }

  /** 初始化消息列表，http请求 */
  private initData (pageQuery: any = { page: 1, limit: this.pageSize }, reset: boolean = true) {
    this.paneLoading = true
    const actionData = Object.assign(pageQuery, this.listQuery)
    if (actionData.type === 'mpNotice') { // mp对接的消息，要新增mptype参数
      actionData.mptype = 'inner'
    }
    MessageModule.MessageCommonAction({
      url: '/base/action/message/list',
      method: 'POST',
      hideLoading: true,
      data: actionData
    }).then(resp => {
      if (resp && resp.success) {
        MessageModule.SET_ACTIVE_XIAO_XI_PANE({
          type: this.listQuery.type,
          list: resp.list,
          count: resp.count,
          noReadCount: resp.noReadCount,
          reset
        })
        return resp
      } else {
        return false
      }
    }).finally(() => {
      this.paneLoading = false
    })
  }

  /** 加载更多 */
  private handleLoadMore () {
    const type = this.listQuery.type
    const page = Math.floor(this.activeMsgListObj[type].length / this.pageSize) + 1
    const limit = this.pageSize
    this.initData({ page, limit }, false)
  }

  /** 每次popover打开时触发 */
  private onPopoverShow () {
    if (this.NoticeDrawerOpen) {
      this.getNoticeNum()
      this.initData()
    }
    this.NoticeDrawerOpen = true
  }

  /** 已读所有消息 */
  private handleAllReadMessage () {
    this.paneLoading = true
    MessageModule.MessageCommonAction({
      url: '/base/action/message/allRead',
      method: 'GET'
    }).then((resp) => {
      if (resp && resp.success) {
        this.initData()
        MessageModule.CLEAR_NO_READ_COUNT()
      }
    }).catch(() => {
      this.paneLoading = false
    })
  }

  /** 删除所有消息 */
  private handleDelReadMessage () {
    MessageModule.MessageCommonAction({
      url: '/base/action/message/delAllRead',
      method: 'GET'
    }).then((resp) => {
      if (resp && resp.success) {
        this.initData()
      }
    }).catch(() => {
      this.paneLoading = false
    })
  }

  /** 星标某条消息（或，取消星标） */
  private handleStarMessage (msg: any) {
    msg.isLoading = true
    MessageModule.MessageCommonAction({
      url: '/base/action/message/star',
      method: 'POST',
      data: {
        id: msg._id,
        isStar: !msg.isStar
      }
    }).then((resp) => {
      if (resp && resp.success) {
        msg.isStar = !msg.isStar
        // 如果当前在星标卡片内，取消星标操作，删除这条消息
        if (this.listQuery.type === 'star' && msg.isStar === false) {
          this.initData()
        }
      }
    }).finally(() => {
      msg.isLoading = false
    })
  }

  /** 阅读某条消息，并打开消息阅读框 */
  private handleReadMessage (msg: any) {
    if (msg.isExpand) {
      // 展开状态，必为已读状态，什么也不做，因为用户可能想选中复制
      // msg.isExpand = false // 收起
    } else {
      // 收起状态
      if (!msg.isRead) {
        // 且为未读状态
        msg.isLoading = true
        MessageModule.MessageCommonAction({
          url: `/base/action/message/read/${msg._id}`,
          method: 'GET'
        }).then((resp) => {
          if (resp && resp.success) {
            msg.isExpand = true // 展开
            msg.isRead = true // 已读
            MessageModule.SUBTRACT_TYPE_NO_READ_COUNT(msg)
          }
        }).finally(() => {
          msg.isLoading = false
          console.log(msg)
        })
      } else {
        msg.isExpand = true
      }
    }
  }

  /** 知道了，收起小面板 */
  private handleIKnow (msg: any) {
    msg.isExpand = false
  }

  /** 查看详情，路由跳转 */
  private handleShowInfo (msg: any) {
    if (msg.type === 'notice') { // 公告
      this.openDraw(msg.noticeId)
    } else if (msg.type === 'mpNotice') { // mp的消息同步（客户，工单）
      this.jumpMpModule(msg)
    } else if (msg.type === 'workorderNotice') {
      if (msg.data && msg.data.messageType) {
        this.$router.push({ name: msg.data.messageType === 'todo' || msg.data.messageType === 'return' ? 'upcoming' : 'pending', params: msg.data })
        emitter.emit('workorderNotice', msg.data);
      } else if (msg.data) {
        // 超时提醒没有messageType，全部跳转到待办
        this.$router.push({ name: 'upcoming', params: msg.data })
        emitter.emit('workorderNotice', msg.data);
      }
    } else if (msg.type === 'qualityCheck') {
      this.$router.push({ name: 'result_query' });
    } else { // 其他（传输中心）
      const path = getBellMessagePath(msg.type, msg.messageKey, msg.transTaskType)
      if (path) {
        this.$router.push(path)
      }
    }
  }

  private async jumpMpModule (msg: any) { // 点击mp的消息跳转详情
    const data = msg && msg.data && msg.data
    const params = { url: '/crm/action/template/query', method: 'POST', data: { worksheetId: data.worksheetId } }
    const result: any = await commonAction(params)
    if (result.success) {
      if (result.data) {
        const routeData = { recordId: data.recordId, viewId: data.viewId, worksheetId: data.worksheetId }
        this.$router.push(result.data.type === 'CUSTOMER' ? `/crm_workBench/index?mpData=${JSON.stringify(routeData)}` : `/ticket_workBench/index?mpData=${JSON.stringify(routeData)}`)
        this.$bus.$emit('updateMpRecord', { type: result.data.type, name: result.data.name, data })
      }
    }
  }

  private async openDraw (id: any) {
    const params = { url: '/base/action/notice/workbench/getNoticeById', method: 'POST', data: { id } }
    const result: any = await commonAction(params)
    if (result.success) {
      const { data } = result
      if (data) {
        this.NoticeDrawer.openDraw(data)
      } else {
        this.$message.error('公告已失效或被删除，无法查看')
      }
    }
  }

  private closeNoticeDrawer () {
    this.NoticeDrawerOpen = false
    setTimeout(() => {
      (this.$refs.xiaoxiPopover as any).doShow()
    }, 0)
  }

  private mounted () {
    this.getNoticeNum() // 初始化红点
  }
}
</script>

<style lang="stylus">
//消息的popover，与app同层级，尽量只修改element原生的样式相关
.xiaoxiElementPopover
  padding 0 !important
  .xiaoxiElementTabs
    .el-tabs--left .el-tabs__nav-wrap.is-left
      padding 0
    .el-tabs--left .el-tabs__nav-wrap.is-left::after
      display none
    .el-tabs--left .el-tabs__header.is-left
      margin-right 0px
    .el-tabs__active-bar
      right initial
    .el-tabs__nav-prev
      display none
    .el-tabs__nav-next
      display none
    .el-tabs__item
      padding 0 16px
      font-size 12px
      height 50px
      line-height 50px
    .el-tabs--left .el-tabs__item.is-left
      color #767E91
      background #F5F9FB
    .el-tabs__item.is-active
      color #008BEE !important
      background #E5F3FD !important
    .el-badge__content
      font-size 12px
      height 16px
      line-height 16px
      padding 0 5px
      border-radius 8px
    .el-badge__content.is-fixed
      top 5px
      right -13px
      border none
      transform initial
      transform scale(0.833)
    .el-tabs__content
      padding 0 16px
      height 100%
      overflow-y auto
</style>

<style scoped lang="stylus">
.xiaoxiPopoverScopedBody
  .xiaoxiHeader
    height 46px
    padding 0 16px
    border-bottom 1px solid #ECF0F3
    display flex
    & > p
      width 80px
      font-size 14px
      line-height 46px
      color #303753
    .xiaoxiHeaderRight
      flex 1
      display flex
      justify-content flex-end
      color #A6A6AE
      line-height 46px
      .V7_iconfont
        font-size 14px
        cursor pointer
      & > i + i
        margin-left 16px
  .xiaoxiCont
    .paneLoadingCont
      position absolute !important
      width 100%
      height 100%
    .emptyPaneCont
      padding 90px
      text-align center
      font-size 12px
      color #767E91
      & > img
        width 100px
      & > p
        margin-top 10px
    .realPaneCont
      font-size 12px
      .msgItemBody + .msgItemBody
        border-top 1px solid #ECF0F3
      .msgItemBody
        padding 14px 0
        .msgItemCont
          cursor pointer
          .msgHeader
            display flex
            line-height 14px
            height 14px
            .msgHeaderLeft
              flex 1
              .msgLevelIcon
                margin-right 6px
                font-size 14px
              .V7_iconV7tubiao_jinjixiaoxi
                color #FC6C5C
              .V7_iconV7tubiao_zhongyaoxiaoxi
                color #FAAE14
              .msgTitle
                color #303753
              .titleReadColor
                color #71798C
              .V7_iconV7tubiao_dian
                font-size 14px
                color #FC6C5C
            .msgHeaderRight
              width 140px
              color #B3B9C7
              //border-left 1px solid red
              text-align right
              .msgStarIcon
                margin-left 4px
                & > i
                  font-size 12px
                  cursor pointer
              .V7_iconV7tubiao_biaoxingxuanzhong
                color #FAAE14
          .msgContainer
            margin-top 10px
            .msgContent
              color #71798C
            .contentReadColor
              color #9499AC
            .msgBtnsBox
              margin-top 10px
              text-align right
              .msgBtn
                width 70px
                height 25px
                color #767E91
                line-height 25px
                background #FFFFFF
                border 1px solid #E7E9ED
                border-radius 13px
                text-align center
                display inline-block
                cursor pointer
              .msgBtn + .msgBtn
                margin-left 10px
              .iKnow
                text-align center
                &:hover
                  color #008BEE
                  border-color #008BEE
                  background-color #e6f4fd
                &:active
                  color #008BEE
                  border-color #008BEE
                  background-color #e6f4fd
              .showInfo
                color #008BEE
                border-color #008BEE
                &:hover
                  color white
                  background-color #008BEE
                &:active
                  color white
                  background-color #008BEE
          .show2line
            overflow hidden
            text-overflow ellipsis
            display -webkit-box
            -webkit-line-clamp 2
            -webkit-box-orient vertical
          .msgLoading
            width 100%
            height 0px
            color #B3B9C7
            text-align right
            img
              width 12px
              vertical-align middle
      .listCountCont
        text-align right
        color #b3b9c7
        padding-bottom 5px
        .loadMore
          text-align center
          cursor pointer
          &:hover
            color #008bee
.xiaoxiToolbarClass
  width 35px
  .V7_iconV7tubiao_xiaoxi
    font-size 18px
    color #3d4e66
    cursor pointer
  .statusIcon
    position absolute
    color #FC6B5C
    top -22px
    right -4px
    cursor pointer
</style>
